#include "vlcrtsp.h"
#include <QDebug>
#include <cstdlib>

VLCRTSP::VLCRTSP(QWidget *parent) : QWidget(parent)
{
    // 设置插件路径 (使用绝对路径)
    QString pluginPath = "D:/QT_code/project/build-untitled2-Desktop_Qt_5_14_2_MinGW_64_bit-Debug/debug/plugins";
    qputenv("VLC_PLUGIN_PATH", pluginPath.toUtf8());

    // 初始化参数
    const char *vlcArgs[] = {
        "--rtsp-tcp",                   // 强制使用TCP传输
        "--network-caching=300",        // 网络缓存300ms
        "--avcodec-hw=none",
        "--avcodec-fast",               // 启用快速解码
        "--quiet",                      // 关闭控制台输出
        "--file-logging",               // 生成日志文件
        "--logfile=vlc.log",            // 日志文件名
        "--verbose=2"                   // 详细日志级别
    };

    // 创建VLC实例
    m_vlcInstance = libvlc_new(sizeof(vlcArgs)/sizeof(vlcArgs[0]), vlcArgs);

    if (!m_vlcInstance) {
        qCritical() << "Failed to initialize VLC instance";
        return;
    }

    // 创建媒体播放器
    m_player = libvlc_media_player_new(m_vlcInstance);
}

VLCRTSP::~VLCRTSP()
{
    stop();
    if (m_player) libvlc_media_player_release(m_player);
    if (m_vlcInstance) libvlc_release(m_vlcInstance);
}

void VLCRTSP::playRTSP(const QString &url)
{
    if (!m_vlcInstance || !m_player) return;

    // 设置播放窗口
    libvlc_media_player_set_hwnd(m_player, (void*)this->winId());

    // 创建媒体对象
    libvlc_media_t *media = libvlc_media_new_location(m_vlcInstance, url.toUtf8().constData());

    if (!media) {
        qWarning() << "Failed to create media for URL:" << url;
        return;
    }

    // 设置播放选项（禁用音频）
    libvlc_media_add_option(media, ":no-audio");

    libvlc_video_set_format(m_player, NULL, 0, 0, 0);

    // 开始播放
    libvlc_media_player_set_media(m_player, media);
    libvlc_media_player_play(m_player);

    // 释放媒体资源
    libvlc_media_release(media);
}

void VLCRTSP::stop()
{
    if (m_player && libvlc_media_player_is_playing(m_player)) {
        libvlc_media_player_stop(m_player);
    }
}

void VLCRTSP::closePlayer()
{
    // 1. 停止播放（若正在播放）
    if (m_player && libvlc_media_player_is_playing(m_player)) {
        libvlc_media_player_stop(m_player);  // 停止播放
    }

    // 2. 释放媒体播放器资源
    if (m_player) {
        libvlc_media_player_release(m_player);  // 销毁播放器对象
        m_player = nullptr;  // 置空指针避免野指针
    }

    // 3. 释放libVLC实例资源
    if (m_vlcInstance) {
        libvlc_release(m_vlcInstance);  // 销毁VLC核心实例
        m_vlcInstance = nullptr;
    }
}
